package bTree.LeetCode;


import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
public class 二叉搜索树中的众数 {
    Map<Integer, Integer> map = new HashMap<>();

    public int[] findMode(TreeNode root) {
        backTracking(root);
        List<Integer>list=new ArrayList<>();
        for (Map.Entry<Integer, Integer> integerIntegerEntry : map.entrySet()) {
            Integer value = integerIntegerEntry.getValue();
            Integer key = integerIntegerEntry.getKey();
            if (list.isEmpty()){
                list.add(key);
            }else {
                Integer preCnt = map.get(list.get(0));
                if(value>preCnt){
                    list.clear();
                    list.add(key);
                }else if (value.equals(preCnt)){
                    list.add(key);
                }
            }
        }
        int[] array = list.stream().mapToInt(Integer::intValue).toArray();
        return array;
    }

    private void backTracking(TreeNode root) {
        if (root==null){
            return;
        }
        int value=root.val;
        if (!map.containsKey(value)){
            map.put(value, 1);
        }else {
            map.put(value, map.get(value)+1);
        }
        backTracking(root.left);
        backTracking(root.right);
    }
}